# coding=utf-8
#import sys

import os
from script import show, uploads, guestbook, data
from web import form
import web
#sys.path.append(os.path.abspath('../'))
os.environ['REAL_SCRIPT_NAME']=""
render= web.template.render('templates/')

#db=web.database(dbn='sqlite',db='guestbook.db')

urls=(
    '/',"index",
    '/guestbook', guestbook.app,
    '/show', show.app,
    '/upload', uploads.app,
    '/login','login',
    '/blog','blog',
    '/reg','register',
    )

class index(object):
    def GET(self):
        #web.header('Content-type','text/html','charset=utf8')
        #name=u'安卫辉!'
        datas=data.comment.all()
        return render.index(datas)

class login:
    def GET(self):
        return render.login()
    def POST(self):
        i = web.input()
        web.setcookie('id', '1')
        web.setcookie('username', i.post_username)
        if i.post_username=='awhhu':
            web.seeother('/show')
        else:
            web.seeother('/blog')

    #def notfound():
    #return notfound("Sorry, the page you are looking for was not found")

class blog:
    def GET(self):
        session = web.cookies()
        web.header('Content-type','text/html','charset=utf8')
        #datas = web.query("SELECT * FROM article where articleAuthor=$session.username", vars=locals())
        print session.username


vpass = form.regexp(r".{3,20}$", 'must be between 3 and 20 characters')
vemail = form.regexp(r".*@.*", "must be a valid email address")
vuser=form.regexp(r'(0-9|a-z|A-Z)*','must be consist of a number')
register_form = form.Form(
    form.Textbox("username", vuser,description="Username"),
    form.Textbox("email", vemail, description="E-Mail"),
    form.Password("password", vpass, description="Password"),
    form.Password("password2", description="Repeat password"),
    form.Button("submit", type="submit", description="Register"),
    validators = [
        form.Validator("Passwords did't match", lambda i: i.password == i.password2)]

)

class register:
    def GET(self):
        # do $:f.render() in the template
        f = register_form()
        return render.register(f)

    def POST(self):
        f = register_form()
        if not f.validates():
            return render.register(f)
        else:
        # do whatever is required for registration
            web.seeother('/show?id=%d' % 1)


if __name__=='__main__':
    app = web.application(urls, globals())
    #app.notfound=notfound
    main = app.cgirun()
    #app.run()
